<?php
/**
 * @package techniv-bb.tcnv-fw
 * @version 0.0.1
 * @copyright © Techniv 2011
 * @license <http://opensource.org/licenses/gpl-3.0.html> GNU General Public License - 3.0
 */

/**
 * Description of TcnvSQL_mysqli
 *
 * @author Vincent
 */
class TcnvSQL_mysqli implements TcnvSQL{
	
	/** @var string */
	private $host, $user, $passwd, $database, $prefix, $port;
	private $configured = false;

	private $connection;

	public function __construct() {
		
	}
	
	public function setConnection($host, $user, $passwd, $database, $prefix = '', $port = '') {
		$this->host = $host;
		$this->port = (isset ($port) && $port!='')? $port : null;
		$this->user = $user;
		$this->passwd = $passwd;
		$this->database = $database;
		$this->prefix = $prefix;
		
		$this->configured = true;
	}
	
	public function isReady() {
		if(!$this->configured) return false;
		$this->connection = mysqli_connect($this->host, $this->user, $this->passwd, $this->database, $this->port);
		if($this->connection == false) return false;
		mysqli_query($this->connection, "SET NAMES 'utf8'");
		return true;
	}
	
	
	public function prefixTable($table_name) {
		return $this->prefix.$table_name;
	}
	
	public function query($sql_query) {
		if(!$this->isReady()) throw new TcnvException ("Impossible de ce connecter à la BDD");
		$result = mysqli_query($this->connection, $sql_query);
		$this->close();
		return $result;
	}

	public function close(){
		mysqli_close($this->connection);
	}

	public function feach_array($result_set) {
		return (!$result_set) ? null : mysqli_fetch_array($result_set);
	}
	
	public function is_set($sql_query) {
		$return = $this->query_array("SELECT EXISTS($sql_query)");
		return $return[0][0];
	}

	public function query_array($sql_query) {
		$result_set = $this->query($sql_query);
		$result = array();
		while($line = $this->feach_array($result_set)){
			$result[] = $line;
		}
		return $result;
	}

}

?>
